package com.hbfec.fileserver.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * 数据源配置类
 */
@Configuration
public class DataSourceConfig {
    /**
     * 业务数据源配置
     *
     * @return Bean
     */
    @Bean(name = "businessDataSourceProperties")
    @Primary
    @ConfigurationProperties("fileserver.datasource.business")
    public DataSourceProperties businessDataSourceProperties() {
        return new DataSourceProperties();
    }

    /**
     * 业务数据源配置
     *
     * @param businessDataSourceProperties businessDataSourceProperties
     * @return Bean
     */
    @Bean(name = "businessDataSource")
    @Primary
    @ConfigurationProperties("fileserver.datasource.business")
    public DataSource businessDataSource(
            @Qualifier("businessDataSourceProperties") DataSourceProperties businessDataSourceProperties) {
        return businessDataSourceProperties.initializeDataSourceBuilder().build();
    }

    /**
     * 业务JdbcTemplate配置
     *
     * @param businessDataSource businessDataSource
     * @return Bean
     */
    @Bean(name = "businessJdbcTemplate")
    @Primary
    public JdbcTemplate businessJdbcTemplate(@Qualifier("businessDataSource") DataSource businessDataSource) {
        return new JdbcTemplate(businessDataSource);
    }

    /**
     * 持久化数据源配置
     *
     * @return Bean
     */
    @Bean(name = "persistDataSourceProperties")
    @ConfigurationProperties("fileserver.datasource.persist")
    public DataSourceProperties persistDataSourceProperties() {
        return new DataSourceProperties();
    }

    /**
     * 持久化数据源配置
     *
     * @param persistDataSourceProperties persistDataSourceProperties
     * @return Bean
     */
    @Bean(name = "persistDataSource")
    @ConfigurationProperties("fileserver.datasource.persist")
    public DataSource persistDataSource(
            @Qualifier("persistDataSourceProperties") DataSourceProperties persistDataSourceProperties) {
        return persistDataSourceProperties.initializeDataSourceBuilder().build();
    }

    /**
     * 持久化JdbcTemplate配置
     *
     * @param persistDataSource persistDataSource
     * @return Bean
     */
    @Bean(name = "persistJdbcTemplate")
    public JdbcTemplate persistJdbcTemplate(@Qualifier("persistDataSource") DataSource persistDataSource) {
        return new JdbcTemplate(persistDataSource);
    }
}
